/*
 * ENUM Discoverer. ENUM Demonstration software, demonstrating the potential of ENUM.
 * 
 * Copyright (C) 2009 SIDN and ISOC.nl
 * 
 * This file is part of ENUM Discoverer.
 *
 * ENUM Discoverer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ENUM Discoverer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ENUM Discoverer.  If not, see <http://www.gnu.org/licenses/>.
 */

package nl.sidn.enumdiscoverer.sync;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import nl.sidn.enumdiscoverer.EditPreferences;
import nl.sidn.enumdiscoverer.EnumClient;
import nl.sidn.enumdiscoverer.LogConfig;
import nl.sidn.enumdiscoverer.R;
import nl.sidn.enumdiscoverer.contacts.dao.ContactsDao;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

/**
 * Periodically polls ENUM DNS server for all contacts and updates Contacts.
 * @author	Grant Patterson (grant.patterson@catalyst.net.nz)
 */
public class EnumSyncService extends Service implements OnSharedPreferenceChangeListener {

	static final String TAG = LogConfig.getLogTag(EnumSyncService.class);
	// whether DEBUG level logging is enabled (whether globally, or explicitly for this log tag)
	static final boolean DEBUG = LogConfig.isDebug(TAG);
	// whether VERBOSE level logging is enabled
	static final boolean VERBOSE = LogConfig.VERBOSE;
	
	private static final long WORKER_SHUTDOWN_TIMEOUT = 2000;  // 2 seconds
	
	
	// application preferences
	private SharedPreferences mPrefs;
	// performs ENUM lookups
	private EnumClient mEnumClient;
	// worker thread for performing the sync tasks
	private ExecutorService mWorker = Executors.newSingleThreadExecutor();
	
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
		mPrefs.registerOnSharedPreferenceChangeListener(this);
		
		mEnumClient = new EnumClient(getDnsSuffixPref(), getDnsServersPref(), getCountryCodePref());
		
		if (VERBOSE) Log.v(TAG, "Created");
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		
		mWorker.execute(new SyncTask());
	}
	
	@Override
	public void onDestroy() {
		
		if (DEBUG) Log.d(TAG, "Shutting down ENUMSync service");
		
		mPrefs.unregisterOnSharedPreferenceChangeListener(this);
		
		// clean up worker
		try {
			boolean timedOut = mWorker.awaitTermination(WORKER_SHUTDOWN_TIMEOUT, TimeUnit.MILLISECONDS);
			if (timedOut) {
				Log.w(TAG, "Timed out waiting for sync worker to stop");
			}
		} catch (InterruptedException e) {
			Log.w(TAG, "Interrupted before sync worker stopped");
		}
		mWorker.shutdownNow();
		mWorker = null;
		
		super.onDestroy();
		
		if (VERBOSE) Log.v(TAG, "Destroyed");
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		
		if (DEBUG) Log.d(TAG, "Preference change detected: " + key);
		
		if        ( key.equals(getString( R.string.pref_custom_dns_key   ))) {
			mEnumClient.setDnsServers(getDnsServersPref());
		} else if ( key.equals(getString( R.string.pref_dns_suffix_key   ))) {
			mEnumClient.setEnumSuffix(getDnsSuffixPref());
		} else if ( key.equals(getString( R.string.pref_country_code_key ))) {
			mEnumClient.setCountryCode(getCountryCodePref());
		}
	}
	
	/*package*/ void syncContacts() {
		
		ContactsDao contactsDao = null;
		
		try {
			
			contactsDao = new ContactsDao(this);
			EnumContactsSync sync = EnumContactsSync.createWithDefaultMapping(contactsDao);
			
			sync.syncAllContacts(mEnumClient);
			
		} finally {
			if (contactsDao != null) contactsDao.close();
		}
	}
	
	private String getDnsSuffixPref() {
		return mPrefs.getString(getString(R.string.pref_dns_suffix_key), null);
	}
	
	private String[] getDnsServersPref() {
		return EditPreferences.getCustomDnsServers(mPrefs, this);
	}
	
	private String getCountryCodePref() {
		String key = getString(R.string.pref_country_code_key);
		return mPrefs.getString(key, null);
	}

	private class SyncTask implements Runnable {
		@Override
		public void run() {
			if (DEBUG) Log.d(TAG, "sync task starting");
			try {
				syncContacts();
			} finally {
				stopSelf();
				if (DEBUG) Log.d(TAG, "sync task done");
			}
		}
	}
}
